import React from 'react'
import {Form, Checkbox, Button, Input, Table} from 'antd'
import T from '../../lib/T'
import api from '../../api'
import ProcessBar from './ProcessBar'

const FormItem = Form.Item
class Basic extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      productDetail: null,
      agreementGoodsId: '',
      channelGoodsId: '',
      planList: [],
      promotionData: null,
      channelGoodsPlanDTOList: [],
      defaultValue: [],
      selectedPlanList: [],
      startSubmit: false,
      lock: false
    }
    this.handleSubmit = this.handleSubmit.bind(this)
    // 查询产品对应的计划
    this.queryProductPlan = this.queryProductPlan.bind(this)
    // 勾选计划
    this.onChangeCheck = this.onChangeCheck.bind(this)
    // 输入计划名字
    this.changePlanName = this.changePlanName.bind(this)
  }

  componentDidMount () {
    let {lock} = this.state
    let agreementGoodsId = T.urlQuery('agreementGoodsId') || ''
    if (agreementGoodsId) {
      this.queryProductPlan(agreementGoodsId)
      this.setState({
        agreementGoodsId
      })
    }
    let {promotionData} = this.props
    if (promotionData && promotionData.agreementGoodsId) {
      !lock && this.queryProductPlan(promotionData.agreementGoodsId)
    }
  }
  componentWillReceiveProps (nextprops) {
    let {lock} = this.state
    let {promotionData} = nextprops
    if (promotionData && !lock) {
      this.setState({lock: true, promotionData})
      if (!lock) {
        this.queryProductPlan(promotionData.agreementGoodsId)
        this.getPlanList(promotionData.channelGoodsPlanDTOList)
      }
    }
  }
  queryProductPlan (agreementGoodsId) {
    T.ajax({
      url: api.queryProductPlan.path,
      data: {agreementGoodsId}
    }).then((res) => {
      if (res.success && res.data) {
        let {selectedPlanList = [], promotionData} = this.state
        // 初始化数据加上后台需要的字段。
        let list = res.data.map(item => {
          item.selected = false
          item.channelGoodsPlanName = item.planName
          return item
        })
        promotionData = promotionData || this.props.promotionData
        // 如果已经编辑过的时候
        if (this.props.promotionData) {
          list = list.map(item => {
            if (selectedPlanList.indexOf(item.planId) > -1) {
              item.selected = true
            }
            return item
          })
          let arr = []
          promotionData.channelGoodsPlanDTOList.forEach(sId => {
            list = list.map(item => {
              if (item.planId === sId.planId) {
                let key = 'input' + sId.planId
                arr.push(sId.planId)
                item.selected = true
                this.setState({
                  [key]: sId.channelGoodsPlanName
                })
                item.channelGoodsPlanName = sId.channelGoodsPlanName
              }
              return item
            })
          })
          this.setState({selectedPlanList: arr})
        }

        this.setState({
          planList: list
        })
      }
    })
  }
  onChangeCheck (e) {
    let {planList = []} = this.state
    let checked = e.target.checked
    let currentPlanId = e.target.value
    planList.map(item => {
      // 选中的planId
      if (item.planId === currentPlanId) {
        checked && (item.selected = true)
        !checked && (item.selected = false)
      }
      return item
    })
    // console.log('planList', planList)
  }
  changePlanName (e, item) {
    let planId = item.planId
    let key = 'input' + planId
    let value = e.target.value
    let {planList = []} = this.state
    this.setState({
      [key]: value
    })
    planList.map(planItem => {
      if (planItem.planId === planId) { // 输入的该编辑框
        planItem.channelGoodsPlanName = value
      }
      return item
    })
    this.setState({
      planList
    })
  }
  handleSubmit (e, btnType) {
    // console.log('this.props', this.props.promotionData)
    e.preventDefault()

    this.props.form.validateFields((err, values) => {
      if (err) return

      let {promotionData} = this.props
      let {channelCompanyId} = this.props.productDetail
      let {channelGoodsName} = values
      let {planList, agreementGoodsId} = this.state
      planList = planList.filter(item => {
        return item.selected && (item.channelGoodsPlanName !== '')
      })
      if (planList.length === 0) return T.showError('Plan item is required')
      let data
      // promotionData不为null时候，说明此步骤已经提交过，接下来是编辑替换。
      if (promotionData) {
        promotionData.channelGoodsPlanDTOList = planList
        promotionData.channelGoodsName = channelGoodsName
        data = Object.assign({}, promotionData, {
          fromStep: 1,
          btnType
        })
      } else {
        // 新增数据
        data = {
          agreementGoodsId,
          channelCompanyId,
          btnType,
          fromStep: 1,
          channelGoodsName,
          channelGoodsPlanDTOList: planList
        }
      }
      console.log('data', data)
      this.props.save(data)
    })
  }
  getPlanList (channelGoodsPlanDTOList = []) {
    let {selectedPlanList} = this.state
    channelGoodsPlanDTOList.forEach(item => {
      let planId = item.planId
      let key = 'input' + planId
      selectedPlanList.push(planId)
      this.setState({
        [key]: item.channelGoodsPlanName
      })
    })
    this.setState({
      selectedPlanList
    })
  }
  render () {
    let {promotionData, tab, basicCompleteStaus, serviceCompleteStaus, saleCompleteStaus} = this.props
    let {planList = []} = this.state
    let {productName = '', insurerName = '', categoryName = ''} = this.props.productDetail

    let {getFieldDecorator} = this.props.form
    let formItemLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 18 }
    }
    let columns = [
      {title: 'Liability', dataIndex: 'liabilityName', wdith: '400', key: 'liabilityName'},
      {title: 'Coverage', dataIndex: 'coverage', key: 'coverage'}
    ]
    if (promotionData) {
      productName = promotionData.productName
      insurerName = promotionData.insurerName
      categoryName = promotionData.categoryName
    }
    return <div className='mt16 basic-info'>
      <div className=''>

        {/* 进度条 */}
        <ProcessBar
          tab={tab}
          save={() => this.handleSubmit(null, 'save')}
          showPreview={this.props.showPreview}
          serviceCompleteStaus={serviceCompleteStaus}
          saleCompleteStaus={saleCompleteStaus}
          basicCompleteStaus={basicCompleteStaus} />

      </div>
      <div className='f16 strong process-sub-title'>
        Basic Information
      </div>
      <Form
        onSubmit={this.handleSubmit}
        className='mt16 basic-form'>
        <FormItem
          {...formItemLayout}
          label={'My Goods：'}>
          {getFieldDecorator('channelGoodsName', {
            initialValue: (promotionData &&
            promotionData.channelGoodsName) || '',
            rules: [{
              required: true,
              message: 'Goods Name is required'
            }]
          })(
            <Input
              maxLength='50'
              style={{'width': '320px'}} />
          )}
        </FormItem>

        <FormItem
          {...formItemLayout}
          label={'Insurance Company :'}>
          { insurerName}
          <span className='insurance-value' >
            Insurance Product : {productName}
          </span>
          <span className='insurance-value'>
            Category : {categoryName}
          </span>
        </FormItem>
        {/* <CheckboxGroup
          onChange={this.onChangeCheck}> */}
        {planList.map((item, index) => {
          return <div key={index} className='mt20 mb20'>
            <Checkbox
              onChange={(e) => {
                this.onChangeCheck(e, item, index)
              }}
              defaultChecked={item.selected}
              value={item.planId}>{item.planName}
            </Checkbox>
            <span className='f14 plan-name'>
                Plan Name：
                <Input
                  maxLength='50'
                  onChange={(e) => {
                    this.changePlanName(e, item)
                  }}
                  placeholder={item.planName}
                  value={this.state['input' + item.planId]}
                  className='plan-input' />
            </span>
            <Table
              className='plan-table'
              columns={columns}
              pagination={false}
              dataSource={item.liabilityResponseDTOList} />

          </div>
        })
          }
        {/* </CheckboxGroup> */}

      </Form>
      <div className='next-btns'>
        <Button
          onClick={(e) => {
            this.handleSubmit(e, 'next')
          }}
          className='next-btn'>Next</Button>
      </div>
    </div>
  }
}

export default Form.create()(Basic)
